package com.itobase.questionnaire.controller;


import com.itobase.questionnaire.model.Questionnaire;
import com.itobase.questionnaire.repository.QuesnaireRepository;
import com.itobase.questionnaire.service.impl.QuesnaireService;
import com.itobase.questionnaire.util.Message;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.itobase.questionnaire.service.IExcelService;

import java.util.Date;
import java.util.List;

@RestController
public class ExcelController {

    @Autowired

    IExcelService excelService;

    @Autowired
    QuesnaireService quesnaireService;

    @Autowired
    QuesnaireRepository quesnaireRepository;

    //excel上传
    @PostMapping("/excel")
    public Message upLoad(@RequestParam String name,@RequestParam MultipartFile file) throws Exception {
        if(name.length()==0){
            Message message = new Message(-1,null,"问卷名字为空");
            return message;
        }else if(name.length()>20){
            Message message = new Message(-1,null,"问卷名字不能超过20个字");
            return message;
        }
        Questionnaire questionnaire_1 = quesnaireRepository.findByName(name);
        if(questionnaire_1==null){
            List<String> list = excelService.upLoad(file);
            Questionnaire questionnaire = quesnaireRepository.findById(list.get(0));
            questionnaire.setName(name);
            questionnaire.setCreateTime(new Date());
            quesnaireService.save(questionnaire);
            list.add(name);
            return Message.createSuc(list);
        }else{
            Message message = new Message(-1,null,"问卷名字重复");
            return message;
        }
    }

    //新建及重命名问卷名
    @PostMapping("/excel/changeName")
    public Message setName(@RequestParam String id, @RequestParam String name) {
        Questionnaire questionnaire = quesnaireService.findById(id);
        if(questionnaire==null){
            return Message.createSuc("问卷id出错，未找到该问卷");
        }else {
            Questionnaire questionnaire_1 = quesnaireRepository.findByName(name);
            if(questionnaire_1!=null){
                return Message.createSuc("该问卷名已存在");
            }else {
                questionnaire.setName(name);
                return Message.createSuc(quesnaireService.update(questionnaire));
            }
        }
    }


}
